<?php

namespace Bean\Flow\PostsFlow;

class Comment extends \Bean\Flow\GenericFlow\Comment {

	private $_data;
	private $_user;
	private $_time;
	private $_post;

	public function __construct( $data, Item $post ) {
		$this->_data = $data;
		$this->_post = $post;
	}
	
	public static function get( $comment_id, Item $post = null ) {
		$comment = _q()->get1( 'posts_comments', array( 'comment_id' => $comment_id ) );
		if( $post === null ) {
			$post = Item::get( $comment['post_id'] );
		}
		return new self( $comment, $post );
	}
	
	public function getMessage() {
		return $this->_data['message'];
	}
	
	public function getPublicationTime() {
		if( $this->_time === null ) {
			$time = strtotime( $this->_data['publication_time'] );
			$this->_time = $time;
		}
		return $this->_time;
	}
	
	public function isLikable( \Bean\User $user = null ) {
		return $this->_post->isLikable( $user );
	}
	
	public function isDeletable( \Bean\User $user = null ) {
		if( $user === null ) {
			$user = _u();
		}
		if( !$user ) {
			return false;
		}
		if( $this->getPost()->isDeletable( $user ) ) {
			return true;
		}
		return $this->getUser()->getUserId() == $user->getUserId();
	}
	
	public function getLikes() {
		
		$n_likes = _q()->getC( 'posts_comments_likes', 
			array( 'comment_id' => $this->getCommentId() ) );
			
		
		switch( $n_likes ) {
			case 0 :
				return false;
			case 1 :
				return '1 person';
			default :
				return $n_likes . ' people';
		}
	}
	
	public function isLikedBy( \Bean\User $user = null ) {
		$user = _u($user);
		if( !$user ) {
			return $this;
		}
		return _q()->getC( 'posts_comments_likes', array(
			'user_id' => $user->getUserId(),
			'comment_id' => $this->getCommentId()
		) ) ? true : false;
	}
	
	public function like( \Bean\User $user = null ) {
		$user = _u($user);
		if( !$user ) {
			return $this;
		}
		_q()->set1(
			'posts_comments_likes',
			array( 
				'user_id' => $user->getUserId(),
				'comment_id' => $this->getCommentId()
			) );
		return $this;
	}
	
	public function unlike( \Bean\User $user = null ) {
		$user = _u($user);
		if( !$user ) {
			return $this;
		}
		_q()->del(
			'posts_comments_likes',
			array( 
				'user_id' => $user->getUserId(),
				'comment_id' => $this->getCommentId()
			) );
		return $this;
	}
	
	public function getCommentId() {
		return $this->_data['comment_id'];
	}
	
	public function getUserId() {
		return $this->_data['user_id'];
	}
	
	public function getPost() {
		return $this->_post;
	}

	public function getUser() {
		if( $this->_user === null ) {
			$this->_user = \Bean\User::get( $this->getUserId() );
		}
		return $this->_user;
	}
	
	public function delete() {
		_q()->del( 'posts_comments_likes',
			array(
				'comment_id' => $this->getCommentId()
			) );
		_q()->del( 'posts_comments',
			array(
				'comment_id' => $this->getCommentId()
			) );
		return $this;
	}
}

